package com.gsc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gsc.constants.SystemConstants;
import com.gsc.domain.ResponseResult;
import com.gsc.domain.entity.Comment;
import com.gsc.domain.vo.CommentVo;
import com.gsc.domain.vo.PageVo;
import com.gsc.enums.AppHttpCodeEnum;
import com.gsc.exception.SystemException;
import com.gsc.mapper.CommentMapper;
import com.gsc.service.UserService;
import com.gsc.utils.BeanCopyUtils;
import com.gsc.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gsc.service.CommentService;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 评论表(Comment)表服务实现类
 *
 * @author makejava
 * @since 2023-02-13 10:13:29
 */
@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    /**
     * 查询评论接口的实现业务
     *
     * @param commentType
     * @param articleId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ResponseResult commentList(String commentType, Long articleId, Integer pageNum, Integer pageSize) {

        //查询对应文章的根评论
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
            //对应的文章：对articleId进行判断
        queryWrapper.eq(SystemConstants.ARTICLE_COMMENT.equals(commentType),Comment::getArticleId,articleId);

            //根评论，rootId为-1  优化：可以将-1改为常量
        queryWrapper.eq(Comment::getRootId,-1);

            //评论类型
        queryWrapper.eq(Comment::getType,commentType);

        //分页查询
        Page<Comment> page = new Page(pageNum,pageSize);
        page(page,queryWrapper);

        //封装到CommentVo中返回给前端，page.getRecords() 获取分页查询后的数据集合
            //直接将Comment集合数据copy到CommentVo中，会导致CommentVo单独有的字段没有copy上，例如：toCommentUserName、username，需手动赋值
        List<CommentVo> commentVoList = toCommentVoList(page.getRecords());

        //查询所有跟评论对应的子评论的集合，并且赋值给对应的属性
        for (CommentVo commentVo : commentVoList) {
            //查询对应的子评论
            List<CommentVo> commentVos = getChildren(commentVo.getId());
            //赋值
            commentVo.setChildren(commentVos);
        }

        return ResponseResult.okResult(new PageVo(commentVoList,page.getTotal()));
    }

    /**
     * 发表评论接口的实现业务
     *
     * @param comment
     * @return
     */
    @Override
    public ResponseResult addComment(Comment comment) {
        //从SecurityContextHolder中获取当前用户的id，不能从前端传，不安全.
//        Long userId = SecurityUtils.getUserId();
//        comment.setCreateBy(userId);
        //评论内容不能为空
        if(!StringUtils.hasText(comment.getContent())){
            throw new SystemException(AppHttpCodeEnum.CONTENT_NOT_NULL);
        }
        //这里已经使用mp自动填充填充好
        save(comment);
        return ResponseResult.okResult();
    }

    /**
     * 根据根评论的id，查询所对应子评论的集合
     * @param id
     * @return
     */

    private List<CommentVo> getChildren(Long id) {

        LambdaQueryWrapper<Comment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Comment::getRootId,id);
        //根据时间进行降序
        lambdaQueryWrapper.orderByAsc(Comment::getCreateTime);

        //查询根评论下的子评论
        List<Comment> comments = list(lambdaQueryWrapper);
        //转换成vo
        List<CommentVo> commentVos = toCommentVoList(comments);

        return commentVos;
    }

    @Autowired
    private UserService userService;

    /**
     * 将Comment集合转换成CommentVo集合，并且填充所有字段
     * @return
     */
    private List<CommentVo> toCommentVoList(List<Comment> list){
        List<CommentVo> commentVos = BeanCopyUtils.copyBeanList(list, CommentVo.class);
        //遍历vo集合，
        for (CommentVo commentVo : commentVos) {
            //通过查询createBy查询用户的昵称并赋值
            String nickName = userService.getById(commentVo.getCreateBy()).getNickName();
            commentVo.setUsername(nickName);
            //通过toCommentUserId查询被回复用户的昵称并赋值
            //如果toCommentUserId不为-1才进行查询
            if(commentVo.getToCommentUserId()!=-1){
                String toCommentUserName = userService.getById(commentVo.getToCommentUserId()).getNickName();
                commentVo.setToCommentUserName(toCommentUserName);
            }
        }
        return commentVos;
    }





}
